<!-- 业务详单查询 -->
<template>
	<div class="ywgzt-container">
		<div class="content">
			<!--高级查询弹窗-->
			<div id="advanced-query-form-dialog">
				<el-dialog v-model="ui.dialogQueryVisible" custom-class="advanced-query-class" :show-close="false">
					<template #title>
						<span style="color: #333; display: inline-block; height: 20px">条件：</span>
						<el-tooltip effect="light" content="该查询为精确查询，请输入准确的查询条件" placement="top-start">
							<i class="question-icon ico-wen">
								<svg-icon icon-class="question" style="color: #333"></svg-icon>
							</i>
						</el-tooltip>
					</template>

					<div>
						<el-form id="advanced-el-form" ref="conforderform" :model="advancedQueryform" inline>
							<!-- 渲染问题列表 -->
							<section v-for="(value, index) in advancedQueryform.queryColumn" :key="index">
								<section v-if="index === 0">
									<el-form-item label="字段" label-width="142px">
										<div>
											<el-select v-model="advancedQueryform.queryColumn[index].column" popper-class="select-coutom" :popper-append-to-body="false">
												<el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
											</el-select>
										</div>
									</el-form-item>
									<el-form-item label="值" label-width="40px">
										<el-input v-model="advancedQueryform.queryColumn[index].value" auto-complete="off" style="width: 200px"></el-input>
									</el-form-item>
									<svg-icon icon-class="orderadd" class="icon-style" circle @click="addItems"></svg-icon>
								</section>
								<section v-if="index > 0">
									<el-form-item>
										<div>
											<el-select
												v-model="advancedQueryform.queryColumn[index].operator"
												popper-class="select-coutom"
												style="width: 70px"
												size="small"
												:popper-append-to-body="false"
											>
												<el-option label="并且" value="and"></el-option>
												<el-option label="或者" value="or"></el-option>
											</el-select>
										</div>
									</el-form-item>
									<el-form-item label="字段">
										<el-select v-model="advancedQueryform.queryColumn[index].column" popper-class="select-coutom" :popper-append-to-body="false">
											<el-option
												v-for="item in options"
												:key="item.value"
												style="background-color: #ff000000"
												:label="item.label"
												:value="item.value"
											></el-option>
										</el-select>
									</el-form-item>
									<el-form-item label="值" label-width="40px">
										<el-input v-model="advancedQueryform.queryColumn[index].value" auto-complete="off" style="width: 200px"></el-input>
									</el-form-item>
									<svg-icon icon-class="orderdel" class="icon-style" circle @click="rmItems(index)"></svg-icon>
								</section>
							</section>
						</el-form>
						<div style="display: flex; justify-content: center">
							<el-row class="mt-20">
								<el-button type="primary" @click="advancedQuery">确认</el-button>
								<el-tooltip effect="light" content="去除高级查询条件筛选" placement="right">
									<el-button @click="clearQuery">取消</el-button>
								</el-tooltip>
							</el-row>
						</div>
					</div>
				</el-dialog>
			</div>
			<yd-form ref="myForm" :options="formOptions" :model="searchFormData" :btns="formBtns"></yd-form>
			<YdTable
				:formData="searchFormData"
				:tableConfig="columnsForm"
				:tableData="tableData"
				@sizeChangeHandler="queryGrid"
				@currentChangeHandler="queryGrid"
				@sortChangeHandler="queryGrid"
			></YdTable>

			<!-- 自定义列弹出层 -->
			<custom-column ref="customColumnRef" pageType="detail"></custom-column>
			<download-panel></download-panel>
		</div>
	</div>
</template>

<script setup name="BusinessDetailQuery" lang="ts">
import { getGrid, download } from '@/api/ops-workbench/historicalAlarm/businessDetail';
import CustomColumn from '@/components/CustomColumn/index.vue';
import useCurrentInstance from '@/utils/useCurrentInstance';
import { useRoute, useRouter } from 'vue-router';
import { ref, reactive, onMounted, nextTick, onActivated } from 'vue';
import useUserStore from '@/store/modules/userinfo';
import { parseTime } from '@/utils/common';
import DownloadPanel from '@/components/DownloadPanel/index.vue';

const { proxy } = useCurrentInstance();
const route = useRoute();
const router = useRouter();
const customColumnRef = ref<any>();
const myForm = ref<any>();

//页面控制
const ui = reactive({
	//高级查询弹窗
	dialogQueryVisible: false,
	//自定义列弹窗
	dialogTableVisible: false,
});
//高级查询表单
const advancedQueryform = reactive({
	queryColumn: [{ operator: 'and', column: 'operatorId', value: '' }],
});
//高级查询下拉列
const options = ref([
	{ label: '营业员工号', value: 'operatorId' },
	{ label: '请求IP', value: 'requestIp' },
	{ label: '响应IP', value: 'responseIp' },
	{ label: '自定义返回码', value: 'customResCode' },
	{ label: '用户标识', value: 'userIdentify' },
]);
const formOptions = reactive<FormOptionType>([
	{
		type: 'select',
		label: '系统名称',
		prop: 'systemId',
		selectKey: 'value',
		api: {
			name: 'queryAppSystemOptions',
			params: { isStatus: 1 },
		},
		cascaders: [
			{
				cascadersParams: 'businessCodeList',
				api: {
					name: 'queryBusinessOptions',
				},
			},
		],
	},
	{
		type: 'select',
		label: '业务名称',
		prop: 'businessCodeList',
		selectKey: 'value',
		attrs: {
			multiple: true,
			indeterminate: false,
		},
	},
	{
		type: 'select',
		label: '业务完整',
		prop: 'completionState',
		selectKey: 'value',
		isInitValue: false,
		children: [
			{ value: 0, label: '不完整' },
			{ value: 1, label: '完整' },
		],
	},
	{
		type: 'select',
		label: '业务状态',
		prop: 'dealState',
		selectKey: 'value',
		isInitValue: false,
		children: [
			{ value: 0, label: '失败' },
			{ value: 1, label: '成功' },
		],
	},
	{
		type: 'select',
		label: '告警类型',
		prop: 'alarmTypeIds',
		selectKey: 'value',
		api: {
			name: 'queryBaseIndicatorsList',
			params: {},
		},
		attrs: {
			multiple: true,
			indeterminate: false,
		},
	},
	{
		type: 'select',
		label: '告警级别',
		prop: 'alarmLevelIds',
		selectKey: 'id',
		api: {
			name: 'queryAlarmLevel',
		},
		attrs: {
			multiple: true,
			indeterminate: false,
		},
	},
	{
		type: 'date-picker',
		label: '时间范围',
		prop: 'dateRange',
		span: 7,
		dateType: 'datetimerange',
		shortcutsKeys: ['last1h', 'today', 'lastDay'],
		defaulShortcutsKey: 'last1h',
	},
	{
		type: 'input',
		label: '专属指标',
		prop: 'exclusiveIndicator',
		attrs: {
			clearable: true,
		},
	},
]);
const formBtns = reactive<BtnType[]>([
	{
		type: 'primary',
		text: '查询',
		handler: searchHandler,
	},
	{
		type: 'primary',
		text: '导出',
		handler: downloadHandler,
	},
	{
		type: 'primary',
		text: '自定义列',
		handler: gridLabelBtnClick,
	},
	{
		type: 'primary',
		text: '高级查询',
		handler: advancedQueryBtnClick,
	},
]);
// 页面是否初始化
const searchFormData = reactive<anyObj>({
	alarmTypeIds: [], //告警类型
	alarmLevelIds: [], //告警级别
	dataCenter: [''],
	systemId: route.query.systemId,
	businessCodeList: route.query.businessCodeList,
	startTime: route.query.startTime,
	endTime: route.query.endTime,
});
const columnsForm = reactive<anyObj>({
	columns: [
		{
			label: '业务名称',
			prop: 'businessName',
		},
		{
			label: '业务状态',
			prop: 'dealState',
		},
		{
			label: '业务完整',
			prop: 'completionState',
		},
		{
			label: '办理时长',
			prop: 'dealTime',
			sortable: 'custom',
		},
		{
			label: '自定义返回码',
			prop: 'customResCode',
		},
		{
			label: '用户标识',
			prop: 'userIdentify',
		},
		{
			label: '用户姓名',
			prop: 'user',
		},
		{
			label: '开始时间',
			prop: 'startTime',
			sortable: 'custom',
		},
		{
			label: '结束时间',
			prop: 'endTime',
			sortable: 'custom',
		},
		{
			label: '告警数',
			prop: 'alarmCount',
			sortable: 'custom',
		},
		{
			label: '专属指标',
			prop: 'exclusiveIndicator',
			// hide: true,
			isExclusive: true,
		},
		{
			label: '操作',
			prop: '',
			operation: [
				{
					text: '详情',
					handler: (scope: anyObj) => {
						router.push({
							path: '/ops-workbench/historicalAlarmQuery/businessDetail/business_detail',
							query: {
								businessDetailId: scope.row.id,
								startTime: searchFormData.startTime,
								startTimeUsec: scope.row.startTimeUsec,
								endTime: searchFormData.endTime,
								endTimeUsec: scope.row.endTimeUsec,
							},
						});
					},
				},
			],
		},
	],
	pagination: {
		pageSize: 10,
		pageNum: 1,
		total: 0,
	},
	loading: true,
	alarmType: true,
});
const tableData = ref([]);

/**
 * 下载
 */
function downloadHandler() {
	let list = [];
	let new_list = [];
	for (let i of columnsForm.columns) {
		if (!i.hide) {
			list.push(i.label);
			new_list.push(i.prop);
		}
	}
	searchFormData.displayMappingFields = new_list;
	searchFormData.displayFields = list;
	searchFormData.systemName = myForm.value.getLabel('systemId');
	let data = {
		submitterId: useUserStore().userInfo?.userId,
		submitterName: useUserStore().userInfo?.username,
		submitTime: parseTime(new Date()),
		serviceCode: 'business-monitor',
		moduleName: 'OPS_WEB_MAIN',
		exportBtnName: '业务详单列表下载',
		docExportParameterJson: JSON.stringify(searchFormData),
		exportFileName: '业务详单列表.xlsx',
		docHandleType: '3',
	};

	download(data).then((response) => {
		proxy.$modal.msgSuccess('已加入下载队列，请查看＂↓＂');
	});
}

/**
 * 搜索按钮
 */
function searchHandler() {
	columnsForm.pagination.pageNum = 1;
	queryGrid();
}

/**
 * 列表查询
 */
function queryGrid() {
	let data = searchFormData;

	if (data.isAlarm === 0) {
		data.alarmTypeIds = [];
	}

	columnsForm.loading = true;
	getGrid(data).then((response: ApiResponse) => {
		if (response.code === 0) {
			for (let i of response.data.data) {
				if (i.explain) {
					i.customResCode = i.customResCode + '(' + i.explain + ')';
				}
			}
			tableData.value = response.data.data;
			columnsForm.pagination.total = response.data.total;
		} else {
			tableData.value = [];
			columnsForm.pagination.total = 0;
			proxy.$modal.msgWarning(response.msg);
		}
		columnsForm.loading = false;
	});
}

/**
 * 自定义列按钮
 */
function gridLabelBtnClick() {
	customColumnRef.value.handleOpen('bpm4.customField.ywgzt.businessDetailList', columnsForm.columns);
}
/**
 * 高级查询按钮
 */
function advancedQueryBtnClick() {
	if (advancedQueryform.queryColumn.length === 0) {
		advancedQueryform.queryColumn.push({
			operator: 'and',
			column: 'operatorId',
			value: '',
		});
	}
	ui.dialogQueryVisible = true;
}
/**
 * 高级查询弹窗，查询按钮
 */
function advancedQuery() {
	let queryColumn: anyObj[] = [];
	//剔除空参
	advancedQueryform.queryColumn.forEach((row, index) => {
		//if (row.value.trim() !== '') {
		queryColumn.push(row);
		// }
	});
	searchFormData.advancedQuery = queryColumn;
	columnsForm.pagination.pageNum = 1;
	queryGrid();
	ui.dialogQueryVisible = false;
}
/**
 * 高级查询弹窗，清空查询按钮
 */
function clearQuery() {
	advancedQueryform.queryColumn = [];
	searchFormData.advancedQuery = [];
	columnsForm.pagination.pageNum = 1;
	queryGrid();
	ui.dialogQueryVisible = false;
}
/**
 * 添加高级查询条件行
 */
function addItems() {
	advancedQueryform.queryColumn.push({
		operator: 'and',
		column: 'operatorId',
		value: '',
	});
	// }
}
/**
 * 删除高级查询条件行
 * @param index 下标
 */
function rmItems(index: number) {
	advancedQueryform.queryColumn.splice(index, 1);
	proxy.$modal.msgSuccess('移除成功');
}

onActivated(() => {
	searchFormData.systemId = route.query.systemId;
	nextTick(() => {
		customColumnRef.value.useCustomColumn('bpm4.customField.ywgzt.businessDetailList', columnsForm.columns);
		searchHandler();
	});
});
onMounted(() => {
	// 初始化自定义列
	nextTick(() => {
		customColumnRef.value.useCustomColumn('bpm4.customField.ywgzt.businessDetailList', columnsForm.columns);
		searchHandler();
	});
});
</script>

<style scoped lang="scss">
:deep(.advanced-query-class) {
	display: flex;
	flex-direction: column;
	margin: 0 !important;
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -60%);
	max-height: calc(100% - 30px);
	max-width: calc(100% - 30px);
	min-width: 800px;
	.el-dialog__body {
		flex: 1;
		// overflow: auto;
	}
	.el-form-item {
		margin-bottom: 0;
	}
	.el-form-item__label {
		color: #fff;
	}
}

#advanced-query-form-dialog section {
	margin-bottom: 10px;
}
</style>
